package com.zmj.dubboannotation.consumermobile.schedule;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSONObject;
import com.zmj.commoncore.constant.RedisConstant;
import com.zmj.commoncore.utils.JsonUtil;
import com.zmj.dubboannotation.consumermobile.redis.RedisUtil;
import com.zmj.dubboannotation.serviceapi.api.MemberActionLogService;
import com.zmj.dubboannotation.serviceapi.model.MemberActionLog;
import lombok.extern.slf4j.Slf4j;
import org.assertj.core.util.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.lang.reflect.Member;
import java.util.List;

/**
 * <p>
 *   用户行为拦截记录 定时入库
 * </p>
 *
 * @Version: 1.0
 * @Author: 周美军
 * @Date: 2018/11/2 13:52
 * @Email: 536304123@QQ.COM
 */
@Component
@Slf4j
public class MemberActionLogSchedule {

    @Reference
    private MemberActionLogService memberActionLogService;

    @Autowired
    private RedisUtil redisUtil;

//    @Scheduled(cron = "0/5 * * * * *")
    public void test() {
        log.info("测试定时...");
    }


    @Scheduled(cron = "0 */20 * * * ?")
//    @Scheduled(cron = "0/5 * * * * *")
    public void insertDB() {
        List<Object> list = redisUtil.listRange(RedisConstant.MEMBER_ACTION_PREFIX, 0, -1);

        if (null != list && list.size() > 0) {
            List<MemberActionLog> lists =  Lists.newArrayList();
            for (Object o: list) {
                //JSONObject jsonObject = JsonUtil.toJSONObject(o);
                //String s = JSONObject.toJSONString(JSONObject.toJSON(o));
                JSONObject parseObject = JSONObject.parseObject(o.toString());
                MemberActionLog memberActionLog1 = JSONObject.toJavaObject(parseObject, MemberActionLog.class);
                //MemberActionLog memberActionLog = JsonUtil.toJavaBean(o, MemberActionLog.class);
                lists.add(memberActionLog1);
            }
            memberActionLogService.insertMore(lists);
            redisUtil.listTrim(RedisConstant.MEMBER_ACTION_PREFIX, lists.size(),-1);
            log.info("[定时任务] MemberActionLogSchedule.insertDB()完成. 入库条数: {}" , lists.size() );
        }else {
            log.info("[定时任务] MemberActionLogSchedule.insertDB() 缓存无数据");
        }

    }
}
